package com.jackeysun.util

import android.content.Context
import android.content.SharedPreferences
import com.jackeysun.util.Application.mApplication
import java.lang.IllegalArgumentException

/**
 *   Created by sunxunchao on 2021/11/19.
 */

object SpExt {
    val mStorage = mApplication.init()
}


fun Context.init(name: String = "sp-info", mode: Int = Context.MODE_PRIVATE): SharedPreferences {
    return getSharedPreferences(name, mode)
}

/**
 * 保存数据
 */
fun SharedPreferences.put(key: String, value: Any): SharedPreferences {
    val editor = this.edit()
    when (value) {
        is Int -> {
            editor.putInt(key, value).apply()
        }
        is String -> {
            editor.putString(key, value).apply()
        }
        is Long -> {
            editor.putLong(key, value).apply()
        }
        is Float -> {
            editor.putFloat(key, value).apply()
        }
        is Boolean -> {
            editor.putBoolean(key, value).apply()
        }
        else -> {
            throw IllegalArgumentException("不支持该类型")
        }
    }
    return this
}

/**
 * 获取保存的数据
 */
fun SharedPreferences.getString(key: String, default: String = ""): String {
    return this.getString(key, default) ?: ""
}

fun SharedPreferences.getInt(key: String, default: Int = 0): Int {
    return this.getInt(key, default)
}

fun SharedPreferences.getBoolean(key: String, default: Boolean = false): Boolean {
    return this.getBoolean(key, default)
}

fun SharedPreferences.getFloat(key: String, default: Float = 0f): Float {
    return this.getFloat(key, default)
}

fun SharedPreferences.getLong(key: String, default: Long = 0L): Long {
    return this.getLong(key, default)
}

fun SharedPreferences.remove(key: String) {
    edit().apply {
        remove(key)
        apply()
    }
}

fun SharedPreferences.clear() {
    edit().apply {
        clear()
        apply()
    }
}


